package com.ocean.tree;

import java.util.*;

/**
 * https://leetcode.cn/problems/binary-tree-inorder-traversal/
 * 中序遍历
 */
public class BinaryTreeInorderTraversal2 {


    public static void main(String[] args) {
        TreeNode root = TreeNode.getRoot();
        BinaryTreeInorderTraversal2 traversal = new BinaryTreeInorderTraversal2();
        List<Integer> res = traversal.inorderTraversal2(root);
        System.out.println(res);
    }

    /**
     * 中序遍历：左->根->右
     * 前序遍历：根->左->右
     * 后序变量：左->右->根
     * 4 2 5 1 6 3
     *
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        inorder(root, res);
        return res;
    }


    private void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        inorder(root.getLeft(), res);
        res.add(root.getValue());
        inorder(root.getRight(), res);
    }


    private List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.getLeft();
            }
            TreeNode cur = stack.pop();
            res.add(cur.getValue());
            root = cur.getRight();
        }
        return res;
    }

}
